﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Xml;
using FineUI;
using Maticsoft.DBUtility;
using mydddd.BLL;
using mydddd.BLL.other;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;


namespace mydddd.admin
{
    public partial class _default : BasePage
    {
        #region Page_Init

        protected void Page_Init(object sender, EventArgs e)
        {
            string menuType = "menu";
            HttpCookie menuCookie = Request.Cookies["MenuStyle_v4"];
            if (menuCookie != null)
            {
                menuType = menuCookie.Value;
            }

            // 注册客户端脚本，服务器端控件ID和客户端ID的映射关系
            JObject ids = GetClientIDS(btnExpandAll, btnCollapseAll, null, mainTabStrip, leftRegion, menuSettings);

            #region 加载左侧功能菜单

     

            //sysModule moduleBll = new sysModule();
            if (Session["Admin"] != null) //管理员
            {
                DataRow dr = Session["Admin"] as DataRow;
                //sysrolepopedom_rname

                //从缓存中读取数据
                DataSet dsTemp =
                    CacheHelper.Get(mydddd.BLL.sysRolepopedom.CacheName() + dr["sysrolepopedom_rname"].ToString()) as DataSet;

                //没有缓存从数据库中读取
                if (dsTemp == null)
                {
                    SysModule moduleBll = new SysModule();
                    dsTemp=moduleBll.GetList(" status=1 and id in (" + dr["moduleid"] + ") order by sort ");
                }

                if (menuType == "accordion")
                {
                    Accordion accordionMenu = new Accordion();
                    accordionMenu.ID = "accordionMenu";
                    accordionMenu.EnableFill = true;
                    accordionMenu.ShowBorder = false;
                    accordionMenu.ShowHeader = false;
                    leftRegion.Items.Add(accordionMenu);

                    BaseTree.CreateAccordion(accordionMenu, dsTemp, "moduleName", "moduleIcon", "parentID", "moduleUrl", "status");

                    ids.Add("mainMenu", accordionMenu.ClientID);
                    ids.Add("menuType", "accordion");
                }
                else
                {
                    FineUI.Tree treeMenu = InitTreeMenu();

                    BaseTree.CreateTree(treeMenu, dsTemp, "moduleName", "moduleIcon", "parentID", "moduleUrl", "status");

                    // 展开第一个树节点
                    try
                    {
                        treeMenu.Nodes[0].Expanded = true;
                    }catch{}

                    ids.Add("mainMenu", treeMenu.ClientID);
                    ids.Add("menuType", "menu");
                }
            }


            #endregion
             
            ids.Add("theme", PageManager.Instance.Theme.ToString());

            // 只在页面第一次加载时注册客户端用到的脚本
            if (!Page.IsPostBack)
            {
                string idsScriptStr = String.Format("window.IDS={0};", ids.ToString(Newtonsoft.Json.Formatting.None));
                PageContext.RegisterStartupScript(idsScriptStr);
            }
        }


        private Tree InitTreeMenu()
        {
            Tree treeMenu = new Tree();
            treeMenu.ID = "treeMenu";
            treeMenu.ShowBorder = false;
            treeMenu.ShowHeader = false;
            treeMenu.EnableIcons = true;
            treeMenu.AutoScroll = true;
            treeMenu.EnableSingleClickExpand = true;
            leftRegion.Items.Add(treeMenu);

            // 绑定 XML 数据源到树控件
            //treeMenu.NodeDataBound += treeMenu_NodeDataBound;
            //treeMenu.DataSource = XmlDataSource1;
            //treeMenu.DataBind();

            //// 重新设置每个节点的图标
            //ResolveTreeNode(treeMenu.Nodes);

            return treeMenu;
        }



        private JObject GetClientIDS(params ControlBase[] ctrls)
        {
            JObject jo = new JObject();
            foreach (ControlBase ctrl in ctrls)
            {
                if (ctrl != null)
                    jo.Add(ctrl.ID, ctrl.ClientID);
            }

            return jo;
        }

        #endregion

        #region Page_Load

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                InitMenuStyleButton();
                InitThemeMenuButton();

            }
        }


        private void InitMenuStyleButton()
        {
            string menuStyleID = "MenuStyleTree";

            HttpCookie menuStyleCookie = Request.Cookies["MenuStyle_v4"];
            if (menuStyleCookie != null)
            {
                switch (menuStyleCookie.Value)
                {
                    case "menu":
                        menuStyleID = "MenuStyleTree";
                        break;
                    case "accordion":
                        menuStyleID = "MenuStyleAccordion";
                        break;
                }
            }


            SetSelectedMenuID(MenuStyle, menuStyleID);
        }




        private void InitThemeMenuButton()
        {
            string themeMenuID = "MenuThemeBlue";

            string themeValue = PageManager1.Theme.ToString().ToLower();
            switch (themeValue)
            {
                case "blue":
                    themeMenuID = "MenuThemeBlue";
                    break;
                case "gray":
                    themeMenuID = "MenuThemeGray";
                    break;
                case "access":
                    themeMenuID = "MenuThemeAccess";
                    break;
                case "neptune":
                    themeMenuID = "MenuThemeNeptune";
                    break;
            }

            SetSelectedMenuID(MenuTheme, themeMenuID);
        }

        #endregion

        #region Event



        protected void MenuTheme_CheckedChanged(object sender, CheckedEventArgs e)
        {
            // 单选框菜单按钮的CheckedChanged事件会触发两次，一次是取消选中的菜单项，另一次是选中的菜单项；
            // 不处理取消选中菜单项的事件，从而防止此函数重复执行两次
            if (!e.Checked)
            {
                return;
            }

            string themeValue = FineUI.Theme.Neptune.ToString();
            string themeID = GetSelectedMenuID(MenuTheme);

            switch (themeID)
            {
                case "MenuThemeNeptune":
                    themeValue = FineUI.Theme.Neptune.ToString();
                    break;
                case "MenuThemeBlue":
                    themeValue = FineUI.Theme.Blue.ToString();
                    break;
                case "MenuThemeGray":
                    themeValue = FineUI.Theme.Gray.ToString();
                    break;
                case "MenuThemeAccess":
                    themeValue = FineUI.Theme.Access.ToString();
                    break;
            }

            SaveToCookieAndRefresh("Theme", themeValue);
        }

        protected void MenuStyle_CheckedChanged(object sender, CheckedEventArgs e)
        {
            // 单选框菜单按钮的CheckedChanged事件会触发两次，一次是取消选中的菜单项，另一次是选中的菜单项；
            // 不处理取消选中菜单项的事件，从而防止此函数重复执行两次
            if (!e.Checked)
            {
                return;
            }

            string menuValue = "menu";
            string menuStyleID = GetSelectedMenuID(MenuStyle);

            switch (menuStyleID)
            {
                case "MenuStyleTree":
                    menuValue = "tree";
                    break;
                case "MenuStyleAccordion":
                    menuValue = "accordion";
                    break;

            }
            SaveToCookieAndRefresh("MenuStyle", menuValue);
        }

        private string GetSelectedMenuID(MenuButton menuButton)
        {
            foreach (MenuItem item in menuButton.Menu.Items)
            {
                if (item is MenuCheckBox && (item as MenuCheckBox).Checked)
                {
                    return item.ID;
                }
            }
            return null;
        }

        private void SetSelectedMenuID(MenuButton menuButton, string selectedMenuID)
        {
            foreach (MenuItem item in menuButton.Menu.Items)
            {
                MenuCheckBox menu = (item as MenuCheckBox);
                if (menu != null && menu.ID == selectedMenuID)
                {
                    menu.Checked = true;
                }
                else
                {
                    menu.Checked = false;
                }
            }
        }


        private void SaveToCookieAndRefresh(string cookieName, string cookieValue)
        {
            HttpCookie cookie = new HttpCookie(cookieName + "_v4", cookieValue);
            cookie.Expires = DateTime.Now.AddYears(1);
            Response.Cookies.Add(cookie);

            PageContext.Refresh();
        }



        #endregion

        //修改密码
        protected void Button_ModifyPassword_OnClick(object sender, EventArgs e)
        {
            if (Session["Admin"] != null)//网站管理员登录
            {
                PageContext.RegisterStartupScript(win_ModifyPassword.GetShowReference("edit.aspx", "修改密码"));
            }
        }

        //注销
        protected void Button_Logout_OnClick(object sender, EventArgs e)
        {
            //Session["Admin"] = null;
            Session.Remove("Admin");
            FormsAuthentication.SignOut();
            //Session.Abandon();//清除全部session

            PageContext.Redirect("~/admin/login.aspx?" + DateTime.Now.ToString("ffff"));

        }
    }
}
